package com.itheima.servlet;

import com.itheima.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/addStudentServlet")
public class addStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        String score = request.getParameter("score");
        Student student = new Student();
        student.setName(name);
        student.setAge(Integer.parseInt(age));
        student.setScore(Integer.parseInt(score));
        String realPath = this.getServletContext().getRealPath("/stu.txt");
        FileInputStream fis = new FileInputStream(realPath);
        if (fis.available() != 0) {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(realPath));
            try {
                ArrayList<Student> list = (ArrayList<Student>) ois.readObject();
                list.add(student);
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(realPath, true));
                oos.writeObject(list);
                oos.close();
                ois.close();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }else {
            ArrayList<Student> list = new ArrayList<>();
            list.add(student);
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(realPath));
            oos.writeObject(list);
            oos.close();
        }

        /*ArrayList<Student> list = new ArrayList<>();
        list.add(student);
        String realPath = this.getServletContext().getRealPath("/stu.txt");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(realPath),"UTF-8"));
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(realPath,true));
        oos.writeObject(student);*/
        PrintWriter writer = response.getWriter();
        writer.print("添加成功!两秒后返回首页!!!");
        //response.sendRedirect(request.getContextPath()+"/index.jsp");错误的,重定向会直接跳转
        response.setHeader("Refresh", "2;" + request.getContextPath() + "/index.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
